"""
Copyright 2009, Ian Blumel.
All Rights Reserved.

Original implemenation idea from David MOhen at
http://www.py2exe.org/index.cgi/BetterCompression.
"""

import os
import sys
from fnmatch import fnmatch

# Indicate what doesn't pass the filter.
excludes = ["python??.dll"]
includes = ["*.dll", "*.pyd"]

def _pass_filter(p):
    f = os.path.basename(p)
    for incl_ptn in includes:
        if fnmatch(f, incl_ptn):
            for excl_ptn in excludes:
                if fnmatch(f, excl_ptn):
                    return False # Includable, but excludable.
                else:
                    return True  # Includable and not excludable.
    return False # Not includable.

def _upx(upx_path, path):
    cmd = "%s --best \"%s\"" % (upx_path, path)
    print >>sys.stdout, cmd
    os.system(cmd)

def _visit_dir(upx_path, dirname, fnames):
    for f in fnames:
        p = os.path.join(dirname, f)
        if os.path.isfile(p) and _pass_filter(p) and not _is_upxed(upx_path, p):
            _upx(upx_path, p)

def dir(dirname, upx_path="upx.exe"):
    """Walks the directory applying "upx" to the elements in an effort to
    shrink the final executable. You can supply the UPX path, but
    default it will run it from the system path."""
    os.path.walk(dirname, _visit_dir, upx_path)
